import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:camera/camera.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'FaceCaptureScreen.dart'; // 用于导航到人脸捕捉屏幕


class FaceSignInScreen extends StatefulWidget {
  const FaceSignInScreen({Key? key}) : super(key: key);

  @override
  _FaceSignInScreenState createState() => _FaceSignInScreenState();
}

class _FaceSignInScreenState extends State<FaceSignInScreen> {
  late String formattedTime = DateFormat('HH:mm:ss').format(DateTime.now());
  Timer? timer;
  List<CameraDescription> _cameras = [];
  String _username = '';
  String _avatarURL = 'http://image.aiyuye.shop/AvatarURL/ic_launcher.png';
  bool _hasSignedInToday = false;

  @override
  void initState() {
    super.initState();
    _initCameras();
    _loadUserInfo();
    _checkSignInStatus();  // 确保在 initState 调用检查签到状态的方法
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final now = DateTime.now();
      final updatedFormattedTime = DateFormat('HH:mm:ss').format(now);
      if (updatedFormattedTime != formattedTime) {
        setState(() {
          formattedTime = updatedFormattedTime;
        });
      }
    });
  }

  Future<void> _checkSignInStatus() async {
    bool signedIn = await isSignInToday();
    setState(() {
      _hasSignedInToday = signedIn;  // 在这里设置变量
    });
  }



  Future<bool> isSignInToday() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String? lastSignInTimeStr = prefs.getString('lastSignInTime');
    if (lastSignInTimeStr == null) {
      if (kDebugMode) {
        print('No sign-in time found.');
      }
      return false;
    }

    DateTime lastSignInTime = DateTime.parse(lastSignInTimeStr);
    DateTime now = DateTime.now();
    bool isToday = lastSignInTime.year == now.year &&
        lastSignInTime.month == now.month &&
        lastSignInTime.day == now.day;

    if (kDebugMode) {
      print('Last sign-in was today: $isToday');
    }
    return isToday;
  }


  Future<void> _loadUserInfo() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _username = prefs.getString('username') ?? '默认用户名';
      _avatarURL = prefs.getString('avatarURL') ?? 'http://image.aiyuye.shop/AvatarURL/ic_launcher.png';
    });
  }
  Future<void> _initCameras() async {
    _cameras = await availableCameras();
  }

  @override
  void dispose() {
    timer?.cancel(); // 取消定时器避免内存泄露
    super.dispose();
  }

  void _navigateToFaceCapture() async {
    // 确保摄像头初始化完成
    if (_cameras.isEmpty) {
      await _initCameras();
    }
    if (_cameras.isNotEmpty) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => SignInCameraScreen(cameras: _cameras),
        ),
      );
    } else {
      _showSignInFalseDialog('错误', '未检测到可用摄像头。');
    }
  }

  void _showSignInFalseDialog(String title,String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(content),
          actions: <Widget>[
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }


  void _handleTap() async {
    if(_hasSignedInToday){
      _showSignInFalseDialog('签到信息', '你今天已经签到过~');
      return;
    }
    var status = await Permission.camera.status;

    if (status.isGranted) {
      _navigateToFaceCapture();
    } else {
      var result = await Permission.camera.request();
      if (result.isGranted) {
        _navigateToFaceCapture();
      } else {
        _showSignInFalseDialog('相机权限', '需要相机权限来进行人脸签到');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('yyyy.MM.dd').format(now);

    return MaterialApp(
      home: Scaffold(
        backgroundColor: const Color(0xFFF8F8F8),
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const SizedBox(height: 40),
                Text(
                  formattedDate,
                  style: const TextStyle(fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    CircleAvatar(
                      radius: 37,
                      backgroundImage: NetworkImage(_avatarURL),
                    ),
                    const SizedBox(width: 10),
                    Text(
                      '你好，$_username',
                      style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                const Center(
                  child: Text(
                    '欢迎使用人脸签到',
                    style: TextStyle(fontSize: 18, color: Colors.grey),
                    textAlign: TextAlign.center,
                  ),
                ),
                Expanded(
                  child: Center(
                    child: GestureDetector(
                      onTap: _handleTap,
                      child: Container(
                        width: 200,
                        height: 200,
                        decoration: BoxDecoration(
                          color: Colors.blueAccent,
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              blurRadius: 10,
                              color: Colors.blue[800]!.withOpacity(0.5), // 使用稍暗的蓝色阴影
                              spreadRadius: 5,
                            ),
                          ],
                        ),
                        child: Icon(
                          _hasSignedInToday ? Icons.check_circle_outline : Icons.person_outline,
                          size: 100,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
                Center(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                    decoration: BoxDecoration(
                      color: Colors.blueAccent,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Text(
                      formattedTime,
                      style: const TextStyle(fontSize: 15, color: Colors.white, fontWeight: FontWeight.bold),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
                const SizedBox(height: 40),
              ],
            ),
          ),
        ),
      ),
    );
  }

}
